<?php
	add_action('draft_to_publish', 'add_mask_link_store');
	add_action('untrash_post', 'add_mask_link_store');
	function add_mask_link_store($post)
	{
		if (is_object($post))
		{
			$type = $post->post_type;
			$ID = $post->ID;
		}
		else
			return;
		if ($type == 'store')
		{
			$target = get_post_meta($ID, 'aff_url_store_metadata', true);
            if($target == '')
                $target = get_post_meta($ID, 'url_store_metadata', true);
			$mask = 's' . $ID;
			$array = array(
				'id' => $ID,
				'type' => $type,
				'target' => $target,
				'mask' => $mask);
			outlink_DB_add($array);
		}
	}
	function outlink_DB_add($array)
	{
		global $wpdb;
		$keys = '';
		$values = '';
		$arr_varchar_keys = array(
			'type',
			'target',
			'mask');
		foreach ($array as $k => $v)
		{
			$keys .= $k . ',';
			if (in_array($k, $arr_varchar_keys))
				$values .= "'$v',";
			else
				$values .= "$v,";

		}
		$keys = substr($keys, 0, -1);
		$values = substr($values, 0, -1);

		$qr = "INSERT INTO {$wpdb->outlink}($keys) VALUES ($values)";
		$rs = $wpdb->query($qr);
	}
	function outlink_DB_update($array)
	{
		global $wpdb;
		$k_v = '';
		$arr_varchar_keys = array(
			'type',
			'target',
			'mask');

		$ID = $array['id'];
		$type = $array['type'];
		foreach ($array as $k => $v)
		{
			if (in_array($k, $arr_varchar_keys))
				$k_v .= "$k='$v',";
			else
				$k_v .= "$k=$v,";
		}
		$k_v = substr($k_v, 0, -1);
		$k_v .= " WHERE id=$ID AND type = '$type'";

		$qr = "UPDATE {$wpdb->outlink} SET $k_v";
		$rs = $wpdb->query($qr);
	}
	function outlink_DB_delete($post_id, $type)
	{
		global $wpdb;
		if (!is_array($post_id) && !$type)
		{
			$qr = "delete from {$wpdb->outlink} where id = $post_id ";
		}
		else
		{
			$ids = '';
			foreach ($post_id as $k => $v)
			{
				if ($k != count($post_id) - 1)
					$ids .= $v . ',';
				else
					$ids .= $v;
			}
			$qr = "delete from {$wpdb->outlink} where id in ($ids) and type = '$type'";
		}
		$rs = $wpdb->query($qr);
	}
	function outlink_DB_checkexist($post_ID, $type)
	{
		global $wpdb;
		$qr = "select count(id) as 'count' from {$wpdb->outlink} where id = $post_ID and type = '$type'";
		$rs = $wpdb->get_results($qr);
		return $rs[0]->count;
	}
